<template>
  <tool-page ref="toolPage" title="生成二维码" :value-length="option.text.length" hiddenOperate>
    <template #value>
      <div class="qr-container">
        <div class="qr-container-item" style="flex: 1; height: 190px">
          <Input
            class="qr-content-text"
            type="textarea"
            placeholder="支持粘贴文本和图片"
            :rows="5"
            v-model="option.text"
            @paste="handlePaste">
          </Input>
        </div>
        <div class="qr-container-item qr-block" style="margin-right: 0">
          <div class="qr-box" @click="$ImagePreview.show({previewList: [dataURI]})">
            <vue-qr
              style="width: 100%;"
              :text="option.text"
              :logoSrc="option.logo"
              :logoMargin="option.logoMargin"
              :logoScale="option.logoScale"
              :logoBackgroundColor="option.logoBackgroundColor"
              :logoCornerRadius="option.logoCornerRadius"
              :correctLevel="option.correctLevel"
              :size="option.size"
              :margin="option.margin"
              :colorDark="option.colorDark"
              :colorLight="option.colorLight"
              :bgSrc="option.bgSrc"
              :gifBgSrc="option.gifBgSrc"
              :backgroundColor="option.backgroundColor"
              :backgroundDimming="option.backgroundDimming"
              :autoColor="option.autoColor"
              :dotScale="option.dotScale"
              :callback="callback"></vue-qr>
          </div>
          <Space>
            <Button type="primary" @click="onDownload">下载</Button>
            <Button type="warning" @click="reset">重置</Button>
          </Space>
        </div>
      </div>
      <div class="qr-operate-container">
        <Form inline :label-width="90">
          <FormItem label="大小" :label-width="40">
            <InputNumber :step="1" v-model="option.size"></InputNumber>
          </FormItem>
          <FormItem :label-width="80">
            <template #label>
              容错级
              <Tooltip content="容错级越高，二维码缺失识别率越高" placement="top-start">
                <Icon type="md-help-circle"/>
              </Tooltip>
            </template>
            <InputNumber :step="1" :min="0" :max="3" v-model="option.correctLevel"></InputNumber>
          </FormItem>
          <FormItem>
            <template #label>
              二维码logo
            </template>
            <Upload action="" accept="image/png, image/jpeg, image/gif, image/jpg"
                    :before-upload="(file) => selectImg(file, 'logo')">
              <Button icon="ios-cloud-upload-outline">选择图片</Button>
            </Upload>
          </FormItem>
          <FormItem :label-width="0">
            <Space>
              <Button type="info" @click="$Copy({text: option.text})">复制文本</Button>
              <Button type="warning" @click="clearImg('logo')">清除logo</Button>
            </Space>
          </FormItem>
        </Form>
        <div class="operate-more">
          <Collapse>
            <Panel name="base">
              基础
              <template #content>
                <Form inline :label-width="90">
                  <FormItem label="实点区颜色">
                    <ColorPicker v-model="option.colorDark" alpha></ColorPicker>
                  </FormItem>
                  <FormItem label="空白区颜色">
                    <ColorPicker v-model="option.colorLight" alpha></ColorPicker>
                  </FormItem>
                  <FormItem :label-width="100">
                    <template #label>
                      <Tooltip content="比例过小可能影响二维码识别率" placement="top-start">
                        <span>实点大小比<Icon type="md-help-circle"/></span>
                      </Tooltip>
                    </template>
                    <InputNumber :step="0.1" :min="0.1" :max="1" v-model="option.dotScale"></InputNumber>
                  </FormItem>
                  <FormItem label="外边框大小">
                    <Input-number :step="1" v-model="option.margin"></Input-number>
                  </FormItem>
                </Form>
              </template>
            </Panel>
            <Panel name="1">
              logo
              <template #content>
                <Form inline :label-width="90">
                  <FormItem>
                    <template #label>
                      <Tooltip content="logo与实点的间距" placement="top-start">
                        <span>空白间距<Icon type="md-help-circle"/></span>
                      </Tooltip>
                    </template>
                    <InputNumber :step="1" :min="0" :max="option.size"
                                 v-model="option.logoMargin"></InputNumber>
                  </FormItem>
                  <FormItem>
                    <template #label>
                      <Tooltip content="logo过大可能造成二维码识别失败，可适当增加容错级来修复" placement="top-start">
                        <span>大小比例<Icon type="md-help-circle"/></span>
                      </Tooltip>
                    </template>
                    <InputNumber :step="0.1" :min="0" :max="0.5" v-model="option.logoScale"></InputNumber>
                  </FormItem>
                  <FormItem label="圆角大小">
                    <InputNumber :step="1" :min="0" :max="option.size * option.logoScale / 2"
                                 v-model="option.logoCornerRadius"></InputNumber>
                  </FormItem>
                  <FormItem label="背景色">
                    <Color-picker v-model="option.logoBackgroundColor" alpha></Color-picker>
                  </FormItem>
                </Form>
              </template>
            </Panel>
            <Panel name="2">
              背景
              <template #content>
                <Form inline :label-width="90">
                  <FormItem :label-width="70">
                    <template #label>
                      <Tooltip content="二维码背景图，空白区为透明时显示" placement="top-start">
                        <span>背景图<Icon type="md-help-circle"/></span>
                      </Tooltip>
                    </template>
                    <Upload action="" accept="image/png, image/jpeg, image/gif, image/jpg"
                            :before-upload="(file) => selectImg(file, 'bgSrc')">
                      <Button icon="ios-cloud-upload-outline">选择图片</Button>
                    </Upload>
                  </FormItem>
                  <FormItem :label-width="0">
                    <Button type="warning" @click="clearImg('bgSrc')">清除背景</Button>
                  </FormItem>
                  <FormItem :label-width="100">
                    <template #label>
                      <Tooltip content="二维码背景图，空白区为透明时显示" placement="top-start">
                        <span>动态背景图<Icon type="md-help-circle"/></span>
                      </Tooltip>
                    </template>
                    <Upload action="" accept="image/gif" :before-upload="(file) => selectImg(file, 'gifBgSrc')">
                      <Button icon="ios-cloud-upload-outline">选择图片</Button>
                    </Upload>
                  </FormItem>
                  <FormItem :label-width="0">
                    <Button type="warning" @click="clearImg('gifBgSrc')">清除动态图</Button>
                  </FormItem>
                  <FormItem :label-width="100">
                    <template #label>
                      <Tooltip content="抽取设置的背景图主要颜色，作为实点颜色" placement="top-start">
                        <span>抽取背景色<Icon type="md-help-circle"/></span>
                      </Tooltip>
                    </template>
                    <Switch
                      v-model="option.autoColor"
                      active-color="#13ce66"
                      inactive-color="#ff4949">
                    </Switch>
                  </FormItem>
                  <FormItem label="背景色" :label-width="60">
                    <Color-picker v-model="option.backgroundColor" alpha></Color-picker>
                  </FormItem>
                  <FormItem :label-width="100">
                    <template #label>
                      <Tooltip content="叠加在背景图上的颜色，在解码有难度的时有一定帮助" placement="top-start">
                        <span>背景叠加色<Icon type="md-help-circle"/></span>
                      </Tooltip>
                    </template>
                    <Color-picker v-model="option.backgroundDimming" alpha></Color-picker>
                  </FormItem>
                </Form>
              </template>
            </Panel>
          </Collapse>
        </div>
      </div>
    </template>
  </tool-page>
</template>

<script>
import vueQr from 'vue-qr/src/packages/vue-qr.vue'
import {FileUtil} from "baitu";
import simpleUtils from "@/utils/simpleUtils";
import FileUtils from "@/utils/FileUtils";
import QrCode from "qrcode-reader";
// import ExportFile from "@/components/ExportFile";

export default {
  name: "QrGenerate",
  data() {
    return {
      dataURI: '',
      logoFileName: '',
      bgFileName: '',
      gifFileName: '',
      option: {
        text: '',
        logo: '',
        logoMargin: 10,
        logoScale: 0.2,
        logoBackgroundColor: '#fff',
        logoCornerRadius: 0,
        correctLevel: 0,
        size: 200,
        margin: 10,
        colorDark: '#000',
        colorLight: '#fff',
        bgSrc: '',
        gifBgSrc: '',
        backgroundColor: '#fff',
        backgroundDimming: null,
        autoColor: true,
        dotScale: 1
      }
    }
  },
  components: {
    vueQr
  },
  methods: {
    clearImg(k1) {
      this.option[k1] = '';
      if (k1 === 'logo') {
        this.logoFileName = ''
      } else if (k1 === 'bgSrc') {
        this.bgFileName = ''
      } else if (k1 === 'gifBgSrc') {
        this.gifFileName = ''
      }
    },
    selectImg(file, k) {
      if (!file) {
        return;
      }
      let reg = /.(jpg|jpeg|png|JPG|PNG)$/
      if (k === 'gifBgSrc') {
        reg = /.(gif|GIF)$/
      }
      if (!reg.test(file.type)) {
        this.$Message({
          message: '图片类型要求：jpeg、jpg、png',
          type: "error"
        });
        return false
      }
      if (k === 'logo') {
        this.logoFileName = file.name || ''
      } else if (k === 'bgSrc') {
        this.bgFileName = file.name || ''
      } else if (k === 'gifBgSrc') {
        this.gifFileName = file.name || ''
      }
      //转化为blob
      FileUtils.fileToBase64(file).then(d => {
        this.option[k] = d;
      })
      return false;
    },
    callback(dataURI) {
      this.dataURI = dataURI;
    },
    onDownload() {
      const file = FileUtils.base64ToFile(this.dataURI, simpleUtils.uuid() + '.png');
      FileUtil.download(file)
      if (this.option.text) {
        this.$refs.toolPage.addHistory(this.option.text, this.$options.name);
        this.$refs.toolPage.refreshHistory(this.$options.name);
      }
    },
    reset() {
      Object.assign(this.$data, this.$options.data())
    },
    handlePaste(event) {
      const clipboardData = event.clipboardData || window.clipboardData;
      if (clipboardData) {
        const items = clipboardData.items;
        if (items && items.length) {
          for (let i = 0; i < items.length; i++) {
            const item = items[i];
            if (item.kind === 'file' && item.type.startsWith('image/')) {
              const imgFile = item.getAsFile();
              if (imgFile) {
                FileUtil.toImage(imgFile).then(res => {
                  const img = res.img
                  const canvas = document.createElement('canvas');
                  canvas.width = img.width;
                  canvas.height = img.height;

                  const ctx = canvas.getContext('2d');
                  ctx.drawImage(img, 0, 0, img.width, img.height);
                  const qr = new QrCode();
                  qr.callback = (err, value) => {
                    if (err) {
                      console.error(err);
                      this.$Message.error('二维码识别失败');
                    } else {
                      this.option.text = value.result
                    }
                  };
                  qr.decode(ctx.getImageData(0, 0, img.width, img.height));
                })
              }
            }
          }
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.qr-container {
  display: flex;
  margin-top: 16px;
  justify-content: space-between;

  .qr-container-item {
    margin-right: 10px;

    .qr-content-text {
      height: 100%;

      :deep(textarea) {
        height: 100%;
      }
    }

    .qr-block {
      display: flex;
      flex-direction: column;
    }
  }

  .qr-box {
    width: 150px;
    height: 150px;
    border: 1px solid #a6a6a6;
    border-radius: 6px;
    overflow: hidden;
  }
}

.qr-operate-container {
  margin-top: 10px;
  font-size: small;

  .operate-more {
    text-align: left;
    font-weight: normal;

    :deep(.ivu-tooltip-inner) {
      white-space: normal;
    }
  }
}
</style>
